package org.androidpn.server.xmpp.push;

import org.androidpn.server.entity.Role;
import org.androidpn.server.entity.Room;
import org.androidpn.server.entity.User;
import org.androidpn.server.xmpp.packet.RoomPacket;
import org.androidpn.server.xmpp.packet.RoomPacket.Operation;
import org.androidpn.server.xmpp.session.ClientSession;
import org.androidpn.server.xmpp.session.SessionManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jivesoftware.smack.util.StringUtils;
import org.xmpp.packet.IQ;

/**
 * This class is to manage sending the room operation to the users.
 * 
 * @author Sehwan Noh (devnoh@gmail.com)
 */
public class RoomManager {

	private static final String NOTIFICATION_NAMESPACE = "androidpn:iq:room";

	private final Log log = LogFactory.getLog(getClass());

	private SessionManager sessionManager;

	/**
	 * Constructor.
	 */
	public RoomManager() {
		sessionManager = SessionManager.getInstance();
	}

	public void sendCloseRoomInstruct(Room room) {
		if (room == null) {
			return;
		}
		for (Role role : room.getRoles()) {
			User user = role.getUser();
			ClientSession session = sessionManager.getSession(user
					.getUsername().toLowerCase());
			if (session != null) {
				RoomPacket roomPacket = new RoomPacket();
				roomPacket.setRoom(room);
				roomPacket.setOperation(Operation.quitRoom);
				IQ iq = new IQ();
				iq.setID("CloseRoomInstruct");
				iq.setTo(session.getAddress());
				if (roomPacket.getChildElementXML() != null) {
					Document doc;
					try {
						doc = DocumentHelper.parseText(roomPacket
								.getChildElementXML());
						Element element = doc.getRootElement();
						iq.setChildElement(element.createCopy());
						iq.setType(IQ.Type.result);
						log.debug("send "
								+ StringUtils.unescapeNode(iq.toXML()));
						session.process(iq);
					} catch (DocumentException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
